package com.whxy02.tolearn.app.controller;

import com.whxy02.tolearn.app.beans.Comment;
import com.whxy02.tolearn.app.beans.Topic;
import com.whxy02.tolearn.app.beans.User;
import com.whxy02.tolearn.app.resultObject.ResultState;
import com.whxy02.tolearn.app.service.CommentService;
import com.whxy02.tolearn.app.service.TopicService;
import com.whxy02.tolearn.app.utils.PackResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/topic")
public class TopicPage {

    @Resource
    CommentService commentService;

    @Resource
    TopicService topicService;

    @Resource
    PackResult packResult;

    @RequestMapping("/publish")
    public Map<String,Object> doPublish(HttpServletRequest request,@RequestParam("details")String details) {
        User user= (User) request.getAttribute("user");
        Topic topic=new Topic();
        topic.setDetails(details);
        topic.setUserId(user.getUserId());
        try {
            topicService.save(topic);
            return packResult.doPackToMap(ResultState.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR,e);
        }

    }


    @RequestMapping("/comment/add")
    public Map<String,Object> doComment(HttpServletRequest request, @RequestParam("topicId")Integer topicId, @RequestParam("details")String details){
        User user= (User) request.getAttribute("user");
        Comment comment=new Comment();
        comment.setDetails(details);
        comment.setUserId(user.getUserId());
        try {
            commentService.save(comment);
            Topic topic= topicService.getById(topicId);
            topic.setCommentId(topic.getCommentId()+comment.getCommentId()+"");
            topicService.change(topic);
            return packResult.doPackToMap(ResultState.SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR,e);
        }

    }
}
